import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import {NavigationProp, useNavigation} from '@react-navigation/native';
import {useAsyncStorage} from '@react-native-async-storage/async-storage';
import {type DataItem} from '@/store';
import {AllNavigatorParamList} from '@/navigator';

export interface FlatListItemProps {
  source: 'Popular' | 'Trending' | 'Favorite';
  index: number;
  value?: DataItem;
  handleUpdate?({id, index}: {id: string; index: number}): void;
}

const FlatListItem: React.FC<FlatListItemProps> = ({
  source,
  index,
  value,
  handleUpdate,
}) => {
  const navigation = useNavigation<NavigationProp<AllNavigatorParamList>>();
  const asyncStorage = useAsyncStorage('favorite');

  const handlePress = () => {
    navigation.navigate('FlatListDetail', {
      source,
      ...value,
    });
  };

  const handleSave = async () => {
    if (value) {
      const storage = await asyncStorage.getItem();
      let data: DataItem[] = [];
      if (!!storage?.length) {
        data = [...JSON.parse(storage)];
      }
      if (!value.isSave) {
        // 收藏
        data.push({...value, isSave: !value.isSave});
      } else {
        // 取消收藏
        data = data.filter(item => item.id !== value.id);
      }
      await asyncStorage.setItem(JSON.stringify(data));
      handleUpdate?.({id: value.id, index});
    }
  };

  return (
    <TouchableOpacity
      style={styles.wrap}
      activeOpacity={0.5}
      onPress={handlePress}>
      <Text style={styles.title}>
        {index + 1}、{value?.title}
      </Text>
      <Text
        style={styles.desc}
        numberOfLines={2} // 限制文本为两行
        ellipsizeMode="tail">
        {value?.desc}
      </Text>
      <View style={styles.bottomWrap}>
        <View style={styles.bottomItemWrap}>
          <Text>Author:</Text>
          <View style={styles.textWrap}>
            <Text style={styles.text}>{value?.author}</Text>
          </View>
        </View>
        <View style={styles.bottomItemWrap}>
          <Text>Star:</Text>
          <View style={styles.textWrap}>
            <Text style={styles.text}>{value?.star}</Text>
          </View>
        </View>
        <TouchableOpacity onPress={handleSave}>
          {value?.isSave ? (
            <MaterialIcons style={styles.star} name="star" size={26} />
          ) : (
            <MaterialIcons name="star-border" size={26} />
          )}
        </TouchableOpacity>
      </View>
    </TouchableOpacity>
  );
};

export default React.memo(FlatListItem);

const styles = StyleSheet.create({
  wrap: {
    paddingTop: 12,
    paddingBottom: 12,
    paddingLeft: 16,
    paddingRight: 16,
    marginTop: 12,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 6,
  },
  desc: {
    fontSize: 12,
    color: '#999',
    marginBottom: 8,
  },
  bottomWrap: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  bottomItemWrap: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  textWrap: {
    marginLeft: 8,
  },
  text: {
    fontSize: 14,
    color: '#999',
  },
  star: {
    color: '#ff7600',
  },
});
